import axios from 'axios';
import qs from 'qs';
// @ts-ignore
import { merge } from 'lodash';


// 通过全局作用域访问 MyAxiosInstance 类型
const http = axios.create({
  // baseURL: process.env.NODE_ENV === 'development'?'/api':'',
  withCredentials: true, // 允许携带cookie
  timeout: 300000, // 请求超时时间
  // headers: { 'Content-Type': 'application/json' }
});

http.interceptors.request.use(
  (config: any) => {
    // const token = localStorage.getItem('token');
    // if (token) config.headers.Authorization = `Bearer ${token}`;
    return config;
  },
  (error: any) => Promise.reject(error)
);

/**
 * post请求数据处理
 * @param {*} data 数据对象
 * @param {*} openDefultdata 是否开启默认数据?
 * @param {*} contentType 数据格式
 *  json: 'application/json; charset=utf-8'
 *  form: 'application/x-www-form-urlencoded; charset=utf-8'
 *  text: 
 */
/*http.adornData = (data = {}, openDefultdata = true, contentType = 'json') => {
  var defaults = {
    't': new Date().getTime()
  }
  data = openDefultdata ? merge(defaults, data) : data
  if(contentType === 'json'){
    return JSON.stringify(data)
  }
  if(contentType === 'form'){
    return qs.stringify(data)
  }
  if(contentType === 'text'){
    return data
  }
//  return contentType === 'json' ? JSON.stringify(data) : qs.stringify(data)
}*/ 

export function getAction(url:string) { 
    return http.get(url)
}

export function postAction() { 

}

// export const getUser = (id) => instance.get(`/user/${id}`);


/**
 * @param url 请求地址
 * @param options fetch 配置项
 * @returns Promise<T> 解析后的响应数据
 */
async function fetchReq<T>(url: string, options?: RequestInit): Promise<T> {
  const response = await fetch(url, {
    ...options,
    headers: {
      'Content-Type': 'application/json',
      ...options?.headers,
    },
  });
 
  if (!response.ok) {
    throw new Error(`HTTP ${response.status}: ${response.statusText}`);
  }
  return response.json() as Promise<T>;
}